package com.kawa.kemanage.service.impl;

import com.kawa.kemanage.entity.NewsDraft;
import com.kawa.kemanage.mapper.NewsDraftMapper;
import com.kawa.kemanage.service.NewsDraftService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 新闻草稿服务实现类
 */
@Service
public class NewsDraftServiceImpl implements NewsDraftService {

    @Autowired
    private NewsDraftMapper newsDraftMapper;

    @Override
    @Transactional
    public NewsDraft saveDraft(NewsDraft draft) {
        if (draft.getId() == null) {
            // 新增草稿
            draft.setCreateDate(LocalDateTime.now());
            draft.setModifyDate(LocalDateTime.now());
            // 设置为草稿状态
            draft.setIsPublish(0);
            if (newsDraftMapper.insertDraft(draft) > 0) {
                return draft; // MyBatis会自动设置生成的ID
            }
        } else {
            // 更新草稿
            draft.setModifyDate(LocalDateTime.now());
            // 设置为草稿状态
            draft.setIsPublish(0);
            if (newsDraftMapper.updateDraft(draft) > 0) {
                return draft;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public boolean deleteDraft(Integer id) {
        return newsDraftMapper.deleteDraftById(id) > 0;
    }

    @Override
    public NewsDraft getDraftById(Integer id) {
        return newsDraftMapper.selectDraftById(id);
    }

    @Override
    public PageInfo<NewsDraft> getDraftList(Integer authorId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<NewsDraft> drafts = newsDraftMapper.selectDraftList(authorId, null, null);
        return new PageInfo<>(drafts);
    }

    @Override
    public List<NewsDraft> getDraftsByAuthorId(Integer authorId) {
        return newsDraftMapper.selectDraftsByAuthorId(authorId);
    }

    @Override
    @Transactional
    public boolean batchDeleteDrafts(List<Integer> ids) {
        int count = 0;
        for (Integer id : ids) {
            if (newsDraftMapper.deleteDraftById(id) > 0) {
                count++;
            }
        }
        return count == ids.size();
    }
}
